package com.jy.api.controller.admin;

import com.jy.api.dao.UserDao;
import com.jy.api.domain.SMSType;
import com.jy.api.domain.User;
import com.jy.api.signUpReq.ResetPwdSignUpReq;
import com.jy.api.util.BCryptUtils;
import com.jy.api.util.Contens;
import com.jy.api.util.ParseErrors;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import java.security.Principal;
import java.util.Set;

/**
 * Created by hanxi on 2017/7/3.
 */
@RestController
@RequestMapping(value = "v1/admin", produces = "application/json;charset=utf-8")
public class LoginController {

    private static Logger logger = LoggerFactory.getLogger(UserController.class);

    private static Validator validator = Validation.buildDefaultValidatorFactory().getValidator();

    @Autowired
    StringRedisTemplate stringRedisTemplate;


    @Autowired
    UserDao userDao;

    @Transactional
    @RequestMapping(method = RequestMethod.POST, value = "/login")
    public void login(@RequestParam(name = "openid", defaultValue = "") String openid,
                      Principal principal) {
        //绑定openID
        if (StringUtils.isNotBlank(openid)) {
            User user = userDao.findByUsername(principal.getName());
            user.setOpenId(openid);
            userDao.save(user);
        }
    }


    @RequestMapping(method = RequestMethod.POST, value = "/authorize")
    public ResponseEntity author(@RequestParam(value = "storeId") String storeId,
                                 Principal principal) {
        try {
            stringRedisTemplate.opsForValue().set(principal.getName(), storeId);
            return new ResponseEntity(HttpStatus.OK);
        } catch (Exception ex) {
            logger.error("admin author is error==> principal{}", principal, ex);
            return new ResponseEntity("系统运行错误", HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    //用户退出登录
    @RequestMapping(method = RequestMethod.POST, value = "/logout")
    public void logout(HttpServletRequest request) {
        SecurityContextLogoutHandler handler = new SecurityContextLogoutHandler();
        handler.logout(request, null, null);
    }

    /**
     * 重置密码
     *
     * @param resetPwdSignUpReq
     * @return
     */
    @RequestMapping(method = RequestMethod.POST, value = "/reset-pwd")
    public ResponseEntity resetPwd(@RequestBody ResetPwdSignUpReq resetPwdSignUpReq) {
        try {
            Set<ConstraintViolation<ResetPwdSignUpReq>> resetPwdErrors =
                    validator.validate(resetPwdSignUpReq);
            if (!resetPwdErrors.isEmpty()) {
                return new ResponseEntity(ParseErrors.getErrors(resetPwdErrors), HttpStatus.BAD_REQUEST);
            }
            String key = Contens.SMS_KEY.replace("MOBILE", resetPwdSignUpReq.getMobile()).
                    replace("TYPE", SMSType.ACCOUNT.toString());
            //从redis中获取code
            String code = stringRedisTemplate.opsForValue().get(key);
            if (!StringUtils.equals(code, resetPwdSignUpReq.getVerifyCode())) {
                return new ResponseEntity("验证码错误", HttpStatus.BAD_REQUEST);
            }
            User user = userDao.findByUsername(resetPwdSignUpReq.getMobile());
            if (user == null) {
                return new ResponseEntity("账号未注册", HttpStatus.BAD_REQUEST);
            }
            user.setPassword(BCryptUtils.encrypt(resetPwdSignUpReq.getPwd()));
            userDao.save(user);
            stringRedisTemplate.delete(key);
            return new ResponseEntity(HttpStatus.OK);
        } catch (Exception ex) {
            logger.error("addJobs is error=>resetPwdSignUpReq:{}", resetPwdSignUpReq, ex);
            return new ResponseEntity("系统运行错误", HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

}
